package com.hundsun.s3.mrs.core.talker;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TalkerManager {
	
	public static final String GROUP_DEF_SINGLE = "groupDefSingle";

	public static final String GROUP_DEF_STAFF = "groupDefStaff";

	public static final String GROUP_DEF_CLIENT = "groupDefClient";

	/**
	 * key为组的名称
	 * value为组
	 */
	private static Map<String, Group> groupMapper = new HashMap<String, Group>();
	
	/**
	 * key位talker的id
	 * value为talker
	 */
	private static Map<String, Talker> talkerMapper = new HashMap<String, Talker>();

	static {
		// 加载三个默认的组
		DefSingleGroup singleGroup = new DefSingleGroup();
		DefClientGroup clientGroup = new DefClientGroup();
		DefStaffGroup staffGroup = new DefStaffGroup();
		groupMapper.put(singleGroup.getId(), singleGroup);
		groupMapper.put(clientGroup.getId(), clientGroup);
		groupMapper.put(staffGroup.getId(), staffGroup);
	}
	
	
	/**
	 * 新增一个组，即给groupMapper添加一个键值对
	 * @param group
	 */
	public static void addGroup(Group group) {
		groupMapper.put(group.getId(), group);
	}
	
	
	/**
	 * 移除一个组，即删除groupMapper的一个键值对
	 * @param groupId
	 * @return
	 */
	public static boolean removeGroup(String groupId) {
		return groupMapper.remove(groupId) != null;
	}
	
	
	/**
	 * 添加一个Talker
	 * @param talker
	 */
	public static void addTalker(Talker talker) {
		talkerMapper.put(talker.getId(), talker);
		List<String> groups = talker.getGroups();
		Iterator<String> iterator = groups.iterator();
		while(iterator.hasNext()) {
			String groupId = iterator.next();
			Group group = groupMapper.get(groupId);
			group.add(talker);
		}
	}
	
	/**
	 * 移除一个talker
	 * @param talkerId
	 * @return
	 */
	public static boolean removeTalker(String talkerId) {
		boolean res = true;
		Talker talker = talkerMapper.get(talkerId);
		List<String> groups = talker.getGroups();
		Iterator<String> iterator = groups.iterator();
		// 移除talkMapper中的人
		res = talkerMapper.remove(talkerId) != null;
		if(!res) {
			return false;
		}
		// 移除组中的人
		while(iterator.hasNext()) {
			String groupId = iterator.next();
			Group group = groupMapper.get(groupId);
			res = group.remove(talker);
		}
		return res;
	}


	public static Map<String, Group> getGroupMapper() {
		return groupMapper;
	}


	public static void setGroupMapper(Map<String, Group> groupMapper) {
		TalkerManager.groupMapper = groupMapper;
	}


	public static Map<String, Talker> getTalkerMapper() {
		return talkerMapper;
	}


	public static void setTalkerMapper(Map<String, Talker> talkerMapper) {
		TalkerManager.talkerMapper = talkerMapper;
	}
	
	public static Talker getTalker(String talkerId) {
		return talkerMapper.get(talkerId);
	}
	
	public static Group getGroup(String groupId) {
		return groupMapper.get(groupId);
	}
}
